// src/components/FlowArea.jsx
import { useState, useRef, useCallback, useEffect } from 'react';
import ReactFlow, { 
  Background,
  Controls,
  MiniMap,
  applyNodeChanges,
  applyEdgeChanges,
  addEdge
} from 'react-flow-renderer';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faPlus, 
  faSave, 
  faPlay,
  faSpinner,
  faServer, 
  faCog,
  faEdit,
  faTrash,
  faChevronRight
} from '@fortawesome/free-solid-svg-icons';
import { getIconByType } from '../utils/icons';
import AgentNode from '../nodes/AgentNode';
import InputNode, { validateInput } from '../nodes/InputNode';
import OutputNode from '../nodes/OutputNode';
import NewAgentModal from './NewAgentModal';
import ToolNode from '../nodes/ToolNode';
import HttpNode from '../nodes/HttpNode';

const nodeTypes = { agentNode: AgentNode, 
                    inputNode: InputNode, 
                    outputNode: OutputNode,
                    toolNode: ToolNode,
                    httpNode: HttpNode
                  };

export default function FlowArea({ agents, workflows, nodes, setNodes, onNodeSelect, edges, setEdges, onSaveWorkflow, handleSaveWorkflow, onCreateAgent, currentWorkflowId, onShowApiPanel, executeWorkflow }) {
  // const [nodes, setNodes] = useState([]);
  // const [edges, setEdges] = useState([]);
  const [showNewAgentModal, setShowNewAgentModal] = useState(false);
  const [isRunning, setIsRunning] = useState(false);
  const [contextMenu, setContextMenu] = useState(null);
  const [selectedNode, setSelectedNode] = useState(null);
  const menuRef = useRef(null);
  // 处理节点变化（拖动等）
  const onNodesChange = useCallback(
    (changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
    [setNodes]
  );
  // 处理连线变化
  const onEdgesChange = useCallback(
    (changes) => setEdges((eds) => applyEdgeChanges(changes, eds)),
    [setEdges]
  );
  // 创建新连线
  const onConnect = useCallback(
    (connection) => setEdges((eds) => addEdge(connection, eds)),
    [setEdges]
  );

  // 处理节点拖放
  const onDrop = useCallback((event) => {
    const agentId = event.dataTransfer.getData('agentId');
    const agentType = event.dataTransfer.getData('agentType');
    const agent = agents.find(a => a.id.toString() === agentId.toString());
    console.log('agentId: ', agentId);
    console.log('agentType: ', agentType);
    console.log('agent: ', agent)
    const position = { 
      x: event.clientX - 240,
      y: event.clientY - 60
    };
    const newNodeId = `${Date.now()}`;
    const baseNode = {
      id: newNodeId,
      position,
      data: {...agent.config}
    };

    console.log('baseNode: ', baseNode);
    console.log('agent.config: ', agent.config);
  
    let newNode;
    switch (agentType) {
      case '输入型':
        newNode = {
          ...baseNode,
          type: 'inputNode',
          data: {
            ...baseNode.data,
            onChange: (value) => {
              setNodes(nds => nds.map(node => {
                if (node.id === newNodeId) {
                  const error = validateInput(node.data.inputType, value);
                  return {
                    ...node,
                    data: { ...node.data, content: value, error: error }
                  };
                }
                return node;
              }));
            },
            onTypeChange: (newType) => {
              setNodes(nds => nds.map(node => {
                if (node.id === newNodeId) {
                  let newContent = '';
                  if (newType === 'boolean') newContent = 'true';
                  if (newType === 'json') newContent = '{}';
    
                  const error = validateInput(newType, newContent);
                  return {
                    ...node,
                    data: { ...node.data, inputType: newType, content: newContent, error }
                  };
                }
                return node;
              }));
            }
          }
        };
        break;
    
      case '输出型':
        newNode = {
          ...baseNode,
          type: 'outputNode',
          data: {
            ...baseNode.data,
            onVariableChange: (value) => {
              setNodes(nds => nds.map(node =>
                node.id === newNodeId
                  ? { ...node, data: { ...node.data, selectedVariable: value } }
                  : node
              ));
            }
          }
        };
        break;
    
      case '对话型':
        newNode = {
          ...baseNode,
          type: 'agentNode',
        };
        break;
    
      case '工具型':
        newNode = {
          ...baseNode,
          type: 'toolNode',
          data: {
            ...baseNode.data,
          }
        };
        break;
      
        case '网络型':
          newNode = {
            ...baseNode,
            type: 'httpNode',
            data: {
              ...baseNode.data,
            }
          };
          break;
    
      default:
        newNode = {
          id: `${Date.now()}`,
          type: 'agentNode',
          position,
          data: { agentId }
        };
        break;
    }
    console.log('newNode: ', newNode);
    setNodes((nds) => nds.concat(newNode));
  }, [agents, setNodes]);

  const handleCreateAgent = (formData) => {
    const newAgent = {
      ...formData,
      id: Date.now()
    };
    onCreateAgent(newAgent);
    setShowNewAgentModal(false);
  };

  // 在组件内添加运行处理函数
  const handleRun = async () => {
    setIsRunning(true);
    try {
      // 检查当前工作流是否已保存
      if (!currentWorkflowId) {
        onSaveWorkflow();
        alert('请先保存工作流再运行。');
        return;
      }
  
      // 自动保存当前工作流
      const currentWorkflow = workflows.find(w => w.id === currentWorkflowId);
      if (currentWorkflow) {
        await handleSaveWorkflow(currentWorkflow.name, 'current');
      }
  
      // 收集输入数据
      const inputNodes = nodes.filter(n => n.type === 'inputNode');
      const inputData = inputNodes.reduce((acc, node) => {
        try {
          acc[node.id] = JSON.parse(node.data.content);
        } catch {
          acc[node.id] = node.data.content;
        }
        return acc;
      }, {});

      console.log('handle run inputData: ', inputData)
  
      // 调用执行API
      const result = await executeWorkflow(currentWorkflowId, inputData);
      // console.log('执行结果:', result['result']);
      // 处理结果，例如更新输出节点
      if (result?.result) {
        const updates = result.result;
        const nodeIdsToUpdate = new Set(Object.keys(updates));
        
        setNodes(prevNodes => 
          prevNodes.map(node => {
            if (nodeIdsToUpdate.has(node.id) && node.type === 'outputNode') {
              // 将数组结果转换为字符串（根据实际需求调整格式）
              const content = Array.isArray(updates[node.id].outputs)
                ? updates[node.id].outputs.join(', ')  // 示例：数组转逗号分隔
                : JSON.stringify(updates[node.id].outputs);
              console.log('hand run node.id: ', content)
              return {
                ...node,
                data: {
                  ...node.data,
                  input_data: updates[node.id]
                }
              };
            }
            return node;
          })
        );
      }
      

    } catch (error) {
      console.error('运行出错:', error);
      alert(`运行失败: ${error.message}`);
    } finally {
      setIsRunning(false);
    }
  };

  // 处理节点右键点击
  const onNodeContextMenu = useCallback((e, node) => {
    e.preventDefault();
    setSelectedNode(node);
    setContextMenu({
      x: e.clientX,
      y: e.clientY,
      type: 'node'
    });
  }, []);

  // 处理画布空白处右键点击
  const onPaneContextMenu = useCallback((e) => {
    e.preventDefault();
    setSelectedNode(null);
    setContextMenu({
      x: e.clientX,
      y: e.clientY,
      type: 'pane'
    });
  }, []);

  // 关闭菜单
  const closeMenu = useCallback(() => setContextMenu(null), []);
  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) {
        closeMenu();
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, [contextMenu, closeMenu]);

  // 删除节点
  const handleDeleteNode = useCallback(() => {
    if (selectedNode) {
      setNodes(nodes => nodes.filter(n => n.id !== selectedNode.id));
      closeMenu();
    }
  }, [selectedNode, closeMenu, setNodes]);

  // 编辑节点
  const handleEditNode = useCallback(() => {
    if (selectedNode) {
      onNodeSelect(selectedNode);
      closeMenu();
    }
  }, [selectedNode, onNodeSelect, closeMenu]);

  // 添加节点
  const handleAddNode = useCallback((agent) => {
    // 复用onDrop逻辑创建节点
    const event = { 
      clientX: contextMenu.x,
      clientY: contextMenu.y,
      dataTransfer: { getData: (key) => {
        if (key === 'agentId') {
            return agent.id;
        } else if (key === 'agentType') {
            return agent.agent_type;
        }
        throw new Error(`Unsupported key: ${key}`);
      }}
    };
    onDrop(event);
    closeMenu();
  }, [contextMenu, closeMenu, onDrop]);

  // 分组agents
  const groupedAgents = agents.reduce((acc, agent) => {
    const type = agent.agent_type;
    if (!acc[type]) acc[type] = [];
    acc[type].push(agent);
    return acc;
  }, {});


  return (
    <div className="flex-1 flex flex-col relative">
      {/* 顶部操作栏 */}
      <div className="h-16 border-b border-gray-200 flex items-center justify-between px-6 bg-white">
        <div className="flex items-center gap-4">
            <button 
              onClick={() => setShowNewAgentModal(true)}
              className="px-4 py-2 bg-primary text-white rounded-button flex items-center gap-2"
            >
              <FontAwesomeIcon icon={faPlus} />
              <span>新建智能体</span>
            </button>
            <button 
              onClick={onSaveWorkflow}
              className="px-4 py-2 border border-gray-300 rounded-button flex items-center gap-2 text-gray-700"
            >
              <FontAwesomeIcon icon={faSave} />
              <span>保存工作流</span>
            </button>
            <button
              onClick={onShowApiPanel} 
              className="px-4 py-2 border border-gray-300 rounded-button flex items-center gap-2 text-gray-700">
              <FontAwesomeIcon icon={faServer} />
              <span>工作流API</span>
            </button>
            <button 
              onClick={handleRun}
              disabled={isRunning}
              className={`px-4 py-2 rounded-button flex items-center gap-2 ${
                isRunning 
                  ? 'bg-gray-400 cursor-not-allowed' 
                  : 'bg-green-500 hover:bg-green-600'
              } text-white transition-colors`}
            >
              <FontAwesomeIcon 
                icon={isRunning ? faSpinner : faPlay} 
                className={isRunning ? 'animate-spin' : ''}
              />
              <span>{isRunning ? '运行中...' : '运行'}</span>
            </button>
          </div>
          <button className="w-10 h-10 flex items-center justify-center text-gray-500 hover:bg-gray-100 rounded-button">
            <FontAwesomeIcon icon={faCog} />
          </button>
      </div>

      {/* React Flow画布 */}
      <ReactFlow
        nodes={nodes}
        edges={edges}
        nodeTypes={nodeTypes}
        // edgesSelectable={true}
        defaultEdgeOptions={{
          style: { 
            strokeWidth: 3,       // 增加默认线宽
            stroke: '#94a3b8',    // 更明显的默认颜色
            cursor: 'pointer'     // 增加指针效果
          },
          animated: false,
        }}
        interaction={{
          edgeUpdaterRadius: 20,  // 增大点击区域半径
          dragEdgeWith: true,     // 允许拖动边
          edgeHovering: true      // 启用悬停检测
        }}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        onNodeContextMenu={onNodeContextMenu}
        onPaneContextMenu={onPaneContextMenu}
        onDrop={onDrop}
        onDragOver={(e) => e.preventDefault()}
        onNodeDoubleClick={(_, node) => onNodeSelect(node)}
      >
        <Background 
          variant="dots" 
          gap={20} 
          size={1} 
          color="#E5E7EB"
        />
        <Controls />
        <MiniMap />
        {contextMenu && (
          <div
            ref={menuRef}
            className="absolute bg-white border border-gray-200 rounded-lg shadow-lg py-2 min-w-[160px] z-50"
            style={{ position: 'fixed', left: contextMenu.x, top: contextMenu.y }}
          >
            {/* 节点操作菜单（保持不变） */}
            {contextMenu.type === 'node' && (
              <>
                <button
                  onClick={handleEditNode}
                  className="w-full px-4 py-2 text-left hover:bg-gray-100 flex items-center gap-2"
                >
                  <FontAwesomeIcon icon={faEdit} />
                  编辑节点
                </button>
                <button
                  onClick={handleDeleteNode}
                  className="w-full px-4 py-2 text-left hover:bg-gray-100 text-red-600 flex items-center gap-2"
                >
                  <FontAwesomeIcon icon={faTrash} />
                  删除节点
                </button>
                <div className="border-t my-1"></div>
              </>
            )}

            {/* 新的三级菜单结构 */}
            <div className="relative group/main">
              <button className="w-full px-4 py-2 text-left hover:bg-gray-100 flex justify-between items-center">
                添加节点
                <FontAwesomeIcon icon={faChevronRight} className="text-xs" />
              </button>
              
              {/* 类型子菜单 */}
              <div className="absolute left-3/4 top-0 ml-1 hidden group-hover/main:block bg-white border rounded-lg shadow-lg min-w-[160px] z-50">
                {Object.entries(groupedAgents).map(([type, agents]) => (
                  <div 
                    key={type} 
                    className="relative group/type hover:bg-gray-50 transition-colors"
                  >
                    <div className="px-4 py-2 flex justify-between items-center cursor-pointer">
                      <span className="text-sm">{type}</span>
                      <FontAwesomeIcon icon={faChevronRight} className="text-xs" />
                    </div>
                    
                    {/* 节点子菜单 */}
                    <div className="absolute left-3/4 top-0 ml-1 hidden group-hover/type:block bg-white border rounded-lg shadow-lg min-w-[160px] z-50">
                      {agents.map(agent => (
                        <button
                          key={agent.id}
                          onClick={() => handleAddNode(agent)}
                          className="w-full px-4 py-2 text-left hover:bg-gray-100 flex items-center gap-2"
                        >
                          <FontAwesomeIcon icon={getIconByType(type)} className="w-4" />
                          <span className="text-sm">{agent.config.label}</span>
                        </button>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </ReactFlow>

      <NewAgentModal
        isOpen={showNewAgentModal}
        onClose={() => setShowNewAgentModal(false)}
        onSubmit={handleCreateAgent}
      />
    </div>
  );
}